package com.atguigu.gulimall.member.interceptor;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.common.constant.AuthConstant;
import com.atguigu.common.to.member.MemberRespTo;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Configuration
public class LoginInterceptor implements HandlerInterceptor {
    public static ThreadLocal<MemberRespTo> threadLocal = new ThreadLocal();
    /**
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        boolean match = new AntPathMatcher().match("/member/**", request.getRequestURI());

        if (match){
            return  true;
        }
        HttpSession session = request.getSession();
        Object object =session.getAttribute(AuthConstant.LOGIN_USER);

        String s = JSON.toJSONString(object);
        //将json转成需要的对象
        MemberRespTo member= JSONObject.parseObject(s,MemberRespTo.class);
        if(member!=null){
            threadLocal.set(member);
            return true;
        }else{
            request.getSession().setAttribute("msg","请先完成登录");
            response.sendRedirect("http://auth.gulimall.com/login.html");
            return false;
        }

    }
}
